﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Drawing;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace S2_Xxxx_XxxNetApi
{
    /// <summary>
    /// String类型的扩展方法类
    /// </summary>
    public static class StringExtensions
    {
        /// <summary>
        /// 判断对象是否为Int32类型的数字
        /// </summary>
        /// <param name="s">传入的字符串</param>
        /// <returns></returns>
        public static bool IsNumeric(this string s)
        {
            if (s != null)
            {
                if (s.Length > 0 && s.Length <= 11 && Regex.IsMatch(s, @"^[-]?[0-9]*[.]?[0-9]*$"))
                {
                    if ((s.Length < 10) || (s.Length == 10 && s[0] == '1') || (s.Length == 11 && s[0] == '-' && s[1] == '1'))
                    {
                        return true;
                    }
                }
            }
            return false;

        }

        /// <summary>
        /// 是否为Double类型
        /// </summary>
        /// <param name="s">传入的字符串</param>
        /// <returns></returns>
        public static bool IsDouble(this string s)
        {
            if (s != null)
            {
                return Regex.IsMatch(s, @"^([0-9])[0-9]*(\.\w*)?$");
            }
            return false;
        }

        /// <summary>
        /// 是否为空
        /// </summary>
        /// <param name="s">传入的字符串</param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 是否不为空
        /// </summary>
        /// <param name="s">传入的字符串</param>
        /// <returns></returns>
        public static bool IsNotNullOrEmpty(this string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// string型转换为bool型
        /// </summary>
        ///<param name="s">传入的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的bool类型结果</returns>
        public static bool ToBoolean(this string s, bool defValue)
        {
            if (s != null)
            {
                if (string.Compare(s.ToUpper(), "TRUE", true) == 0)
                {
                    return true;
                }
                else if (string.Compare(s.ToUpper(), "FALSE", true) == 0)
                {
                    return false;
                }
            }
            return defValue;
        }

        /// <summary>
        /// object类型可空地转换字符串类型
        /// </summary>
        /// <param name="o">传入的字符串</param>
        /// <returns></returns>
        public static string ToNullString(this object o)
        {
            if (o != null && !string.IsNullOrEmpty(o.ToString()))
            {
                return o.ToString();
            }
            return null;
        }

        /// <summary>
        /// object类型可空地转换字符串类型
        /// </summary>
        /// <param name="o">传入的字符串</param>
        /// <returns></returns>
        public static string ToEmptyString(this object o)
        {
            if (o != null && !string.IsNullOrEmpty(o.ToString()))
            {
                return o.ToString();
            }
            return "";
        }

        /// <summary>
        /// 将对象转换为Int32类型
        /// </summary>
        /// <param name="defValue">缺省值</param>
        /// <param name="s">传入的字符串</param>
        /// <returns>转换后的int类型结果</returns>
        public static Int32 ToInt32(this string s, int defValue)
        {

            if (s != null)
            {
                if (s.Length > 0 && s.Length <= 11 && Regex.IsMatch(s, @"^[-]?[0-9]*$"))
                {
                    if ((s.Length < 10) || (s.Length == 10 && s[0] == '1') || (s.Length == 11 && s[0] == '-' && s[1] == '1'))
                    {
                        return Convert.ToInt32(s);
                    }
                }
            }
            return defValue;
        }

        /// <summary>
        /// 将对象转换为Int16类型
        /// </summary>
        /// <param name="defValue">缺省值</param>
        /// <param name="s">传入的字符串</param>
        /// <returns>转换后的int类型结果</returns>
        public static Int16 ToInt16(this string s, Int16 defValue)
        {

            if (s != null)
            {
                if (s.Length > 0 && s.Length <= 11 && Regex.IsMatch(s, @"^[-]?[0-9]*$"))
                {
                    if ((s.Length < 10) || (s.Length == 10 && s[0] == '1') || (s.Length == 11 && s[0] == '-' && s[1] == '1'))
                    {
                        return Convert.ToInt16(s);
                    }
                }
            }
            return defValue;
        }

        /// <summary>
        /// string型转换为float型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static float ToFloat(this string strValue, float defValue)
        {
            if ((strValue == null) || (strValue.Length > 10))
                return defValue;

            float intValue = defValue;
            if (strValue != null)
            {
                bool IsFloat = Regex.IsMatch(strValue, @"^([-]|[0-9])[0-9]*(\.\w*)?$");
                if (IsFloat)
                    float.TryParse(strValue, out intValue);
            }
            return intValue;
        }

        /// <summary>
        /// string型转换为float型
        /// </summary>
        /// <param name="s">传入的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static Single ToSingle(this string s, Single defValue)
        {
            if ((s == null) || (s.ToString().Length > 10))
            {
                return defValue;
            }

            Single value = defValue;
            if (s != null)
            {
                bool isFloat = Regex.IsMatch(s.ToString(), @"^([-]|[0-9])[0-9]*(\.\w*)?$");
                if (isFloat)
                {
                    value = Convert.ToSingle(s);
                }
            }
            return value;
        }

        /// <summary>
        /// string型转换为decimal型
        /// </summary>
        /// <param name="s">传入的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static decimal ToDecimal(this string s, decimal defValue)
        {
            if ((s == null))
            {
                return defValue;
            }

            decimal value = defValue;
            if (s != null)
            {
                bool isDecimal = Regex.IsMatch(s.ToString(), @"^([-]|[0-9])[0-9]*(\.\w*)?$");
                if (isDecimal)
                {
                    value = Convert.ToDecimal(s);
                }
            }
            return value;
        }

        /// <summary>
        /// 判断字符串是否是int/double
        /// </summary>
        public static bool IsIntOrDouble(this string strNumber)
        {
            Regex objNotNumberPattern = new Regex("[^0-9.-]");
            Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
            Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
            const string strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
            const string strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
            Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");
            return !objNotNumberPattern.IsMatch(strNumber) &&
             !objTwoDotPattern.IsMatch(strNumber) &&
             !objTwoMinusPattern.IsMatch(strNumber) &&
             objNumberPattern.IsMatch(strNumber);
        }


        /// <summary>
        /// string型转换为DateTime类型
        /// </summary>
        /// <param name="s">传入的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的DateTime类型结果</returns>
        public static DateTime ToDateTime(this string s, DateTime defValue)
        {
            if (s == null)
            {
                return defValue;
            }
            else
            {
                try
                {
                    return Convert.ToDateTime(s);
                }
                catch
                {
                    return defValue;
                }
            }
        }

        /// <summary>
        /// string型转换为DateTime类型
        /// </summary>
        /// <param name="s">传入的字符串</param>
        /// <returns>转换后的DateTime类型结果</returns>
        public static DateTime? ToDateTime(this string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return null;
            }
            else
            {
                try
                {
                    DateTime time = DateTime.Parse(s);

                    return time;
                }
                catch
                {
                    return null;
                }
            }
        }

        /// <summary>       
        /// 作用：将字符串内容转化为16进制数据编码，其逆过程是Decode         
        /// 参数说明：
        /// strEncode 需要转化的原始字符串         
        /// 转换的过程是直接把字符转换成Unicode字符,比如数字"3"-->0033,汉字"我"-->U+6211         
        /// 函数decode的过程是encode的逆过程.         
        /// </summary>         
        /// <param name="strEncode"></param>         
        /// <returns></returns>         
        public static string EncodeToHex16(this string strEncode)
        {
            string strReturn = "";//  存储转换后的编码             
            foreach (short shortx in strEncode.ToCharArray())
            {
                strReturn += shortx.ToString("X4");
            }
            return strReturn;
        }

        /// <summary>             
        /// 作用：将16进制数据编码转化为字符串，是Encode的逆过程         
        /// </summary>         
        /// <param name="strDecode"></param>         
        /// <returns></returns>         
        public static string Hex16Decode(this string strDecode)
        {
            string sResult = "";
            for (int i = 0; i < strDecode.Length / 4; i++)
            {
                sResult += (char)short.Parse(strDecode.Substring(i * 4, 4), global::System.Globalization.NumberStyles.HexNumber);
            }
            return sResult;
        }


        /// <summary>
        /// string型转换为DateTime类型
        /// </summary>
        /// <param name="s">传入的字符串</param>
        /// <returns>转换后的DateTime类型结果</returns>
        public static DateTime? ToHasNullDateTime(this string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return null;
            }
            else
            {
                try
                {
                    return Convert.ToDateTime(s);
                }
                catch
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 返回字符串真实长度, 1个汉字长度为2
        /// </summary>
        /// <returns>字符长度</returns>
        public static int GetStringLength(this string str)
        {
            return Encoding.Default.GetBytes(str).Length;
        }

        /// <summary> 
        /// 是否是浮点数 可带正负号 
        /// </summary> 
        /// <param name="inputData">输入字符串 </param> 
        /// <returns> </returns> 
        public static bool IsDecimalSign(this string str)
        {
            Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$");
            Match m = RegDecimalSign.Match(str);
            return m.Success;
        }

        /// <summary>
        /// 是否为ip
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(this string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");

        }

        public static bool IsIPSect(this string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){2}((2[0-4]\d|25[0-5]|[01]?\d\d?|\*)\.)(2[0-4]\d|25[0-5]|[01]?\d\d?|\*)$");
        }

        /// <summary>
        /// 检测是否符合email格式
        /// </summary>
        /// <param name="strEmail">要判断的email字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsEmail(this string strEmail)
        {
            return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        /// <summary>
        /// 检测是否是正确的Url
        /// </summary>
        /// <param name="strUrl">要验证的Url</param>
        /// <returns>判断结果</returns>
        public static bool IsURL(this string strUrl)
        {
            return Regex.IsMatch(strUrl, @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
        }

        /// <summary>
        /// 判断是否为base64字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsBase64String(this string str)
        {
            //A-Z, a-z, 0-9, +, /, =
            return Regex.IsMatch(str, @"[A-Za-z0-9\+\/\=]");
        }

        /// <summary>
        /// 检测是否有Sql危险字符
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsSafeSqlString(this string str)
        {

            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
        }

        /// <summary>
        /// 根据指定的长度截取字符串
        /// </summary>
        /// <param name="strInput">字符串</param>
        /// <param name="len">长度</param>
        /// <returns></returns>
        public static string ToCut(this string strInput, int len)
        {
            if (!string.IsNullOrEmpty(strInput))
            {
                strInput = strInput.Trim();
                int byteLen = Encoding.GetEncoding("gb2312").GetByteCount(strInput);
                if (byteLen > len)
                {
                    string resultStr = "";
                    for (int i = 0; i < strInput.Length; i++)
                    {
                        if (Encoding.GetEncoding("gb2312").GetByteCount(resultStr) < len - 2)
                        {
                            resultStr += strInput.Substring(i, 1);
                        }
                        else
                        {
                            break;
                        }
                    }
                    return resultStr + "...";
                }
                else
                {
                    return strInput;
                }
            }
            return "";
        }

        /// <summary>
        /// 移除掉字符串最后一个字符，比如，
        /// </summary>
        /// <param name="strInput">输入字符，null时返回“”</param>
        /// <param name="str">要截取的字符串</param>
        /// <returns></returns>
        public static string CutFirstChar(this string strInput, string str)
        {
            if (!string.IsNullOrEmpty(strInput))
            {
                while (strInput.StartsWith(str))
                {
                    strInput = strInput.Remove(0, 1);
                }
                return strInput;
            }
            return "";
        }

        /// <summary>
        /// 移除掉字符串最后一个字符，比如，
        /// </summary>
        /// <param name="strInput">输入字符，null时返回“”</param>
        /// <param name="str">要截取的字符串</param>
        /// <returns></returns>
        public static string CutLastChar(this string strInput, string str)
        {
            if (!string.IsNullOrEmpty(strInput))
            {
                while (strInput.EndsWith(str))
                {
                    strInput = strInput.Remove(strInput.Length - 1, 1);
                }
                return strInput;
            }
            return "";
        }

        /// <summary>
        /// 去掉头部和尾部的字符
        /// </summary>
        /// <param name="strInput">输入字符，null时返回""</param>
        /// <param name="str">要截取的字符串</param>
        /// <returns></returns>
        public static string TrimChar(this string strInput, string str)
        {
            return strInput.CutFirstChar(str).CutLastChar(str);
        }

        /// <summary>
        /// 取指定长度的字符串
        /// </summary>
        /// <param name="p_SrcString">要检查的字符串</param>
        /// <param name="p_StartIndex">起始位置</param>
        /// <param name="p_Length">指定长度</param>
        /// <param name="p_TailString">用于替换的字符串</param>
        /// <returns>截取后的字符串</returns>
        public static string ToCut(this string p_SrcString, int p_StartIndex, int p_Length, string p_TailString)
        {
            string myResult = p_SrcString;

            if (p_Length >= 0)
            {
                byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString);

                //当字符串长度大于起始位置
                if (bsSrcString.Length > p_StartIndex)
                {
                    int p_EndIndex = bsSrcString.Length;

                    //当要截取的长度在字符串的有效长度范围内
                    if (bsSrcString.Length > (p_StartIndex + p_Length))
                    {
                        p_EndIndex = p_Length + p_StartIndex;
                    }
                    else
                    {   //当不在有效范围内时,只取到字符串的结尾

                        p_Length = bsSrcString.Length - p_StartIndex;
                        p_TailString = "";
                    }



                    int nRealLength = p_Length;
                    int[] anResultFlag = new int[p_Length];
                    byte[] bsResult = null;

                    int nFlag = 0;
                    for (int i = p_StartIndex; i < p_EndIndex; i++)
                    {

                        if (bsSrcString[i] > 127)
                        {
                            nFlag++;
                            if (nFlag == 3)
                            {
                                nFlag = 1;
                            }
                        }
                        else
                        {
                            nFlag = 0;
                        }

                        anResultFlag[i] = nFlag;
                    }

                    if ((bsSrcString[p_EndIndex - 1] > 127) && (anResultFlag[p_Length - 1] == 1))
                    {
                        nRealLength = p_Length + 1;
                    }

                    bsResult = new byte[nRealLength];

                    Array.Copy(bsSrcString, p_StartIndex, bsResult, 0, nRealLength);

                    myResult = Encoding.Default.GetString(bsResult);

                    myResult = myResult + p_TailString;
                }
            }

            return myResult;
        }

        /// <summary>
        /// 字符串如果超过指定长度则将超出的部分用指定字符串代替
        /// </summary>
        /// <param name="p_SrcString">要检查的字符串</param>
        /// <param name="p_Length">指定长度</param>
        /// <param name="p_TailString">用于替换的字符串</param>
        /// <returns>截取后的字符串</returns>
        public static string ToCut(this string p_SrcString, int p_Length, string p_TailString)
        {
            return ToCut(p_SrcString, 0, p_Length, p_TailString);
        }

        /// <summary>
        /// 返回 HTML 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string HtmlEncode(this string str)
        {
            return HttpUtility.HtmlEncode(str);
        }

        /// <summary>
        /// 返回 HTML 字符串的解码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string HtmlDecode(this string str)
        {
            return HttpUtility.HtmlDecode(str);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string UrlEncode(this string str)
        {
            return HttpUtility.UrlEncode(str);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string UrlDecode(this string str)
        {
            return HttpUtility.UrlDecode(str);
        }

        /// <summary>
        /// 合并字符
        /// </summary>
        /// <param name="source">要合并的源字符串</param>
        /// <param name="target">要被合并到的目的字符串</param>
        /// <param name="mergechar">合并符</param>
        /// <returns>并到字符串</returns>
        public static string MergeString(this string source, string target, string mergechar)
        {
            if (target.StrIsNullOrEmpty())
                target = source;
            else
                target += mergechar + source;

            return target;
        }

        /// <summary>
        /// 合并字符
        /// </summary>
        /// <param name="source">要合并的源字符串</param>
        /// <param name="target">要被合并到的目的字符串</param>
        /// <param name="mergechar">合并符</param>
        /// <returns>合并到的目的字符串</returns>
        public static string MergeString(this string source, string target)
        {
            return source.MergeString(target, ",");
        }

        /// <summary>
        /// 获取指定文件的扩展名
        /// </summary>
        /// <param name="fileName">指定文件名</param>
        /// <returns>扩展名</returns>
        public static string GetFileExtName(this string fileName)
        {
            if (fileName.StrIsNullOrEmpty() || fileName.IndexOf('.') <= 0)
                return "";

            fileName = fileName.ToLower().Trim();

            return fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.'));
        }

        /// <summary>
        /// 过滤HTML中的不安全标签
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveUnsafeHtml(this string content)
        {
            content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
            content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
            return content;
        }

        /// <summary>
        /// Json特符字符过滤，参见http://www.json.org/
        /// </summary>
        /// <param name="sourceStr">要过滤的源字符串</param>
        /// <returns>返回过滤的字符串</returns>
        public static string JsonCharFilter(this string sourceStr)
        {
            sourceStr = sourceStr.Replace("\\", "\\\\");
            sourceStr = sourceStr.Replace("\b", "\\\b");
            sourceStr = sourceStr.Replace("\t", "\\\t");
            sourceStr = sourceStr.Replace("\n", "\\\n");
            sourceStr = sourceStr.Replace("\n", "\\\n");
            sourceStr = sourceStr.Replace("\f", "\\\f");
            sourceStr = sourceStr.Replace("\r", "\\\r");
            return sourceStr.Replace("\"", "\\\"");
        }

        /// <summary>
        /// 将传入的字符串中间部分字符替换成特殊字符
        /// </summary>
        /// <param name="value">需要替换的字符串</param>
        /// <param name="startLen">前保留长度</param>
        /// <param name="endLen">尾保留长度</param>
        /// <param name="specialChar">特殊字符</param>
        /// <returns>被特殊字符替换的字符串</returns>
        public static string ReplaceWithSpecialChar(this string value, int startLen = 10, int endLen = 2, char specialChar = '*')
        {
            if (value.Length >= 18)
            {
                try
                {
                    int lenth = value.Length - startLen - endLen;
                    string replaceStr = value.Substring(startLen, lenth);
                    string specialStr = string.Empty;
                    for (int i = 0; i < replaceStr.Length; i++)
                    {
                        specialStr += specialChar;
                    }

                    value = value.Replace(replaceStr, specialStr);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            return value;
        }


        /// <summary>
        /// 根据Url获得源文件内容
        /// </summary>
        /// <param name="url">合法的Url地址</param>
        /// <returns></returns>
        public static string GetSourceTextByUrl(this string url)
        {
            WebRequest request = WebRequest.Create(url);
            request.Timeout = 20000;//20秒超时
            WebResponse response = request.GetResponse();

            Stream resStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(resStream);
            return sr.ReadToEnd();
        }

        /// <summary>
        /// 字段串是否为Null或为""(空)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool StrIsNullOrEmpty(this string str)
        {
            if (str == null || str.Trim() == string.Empty)
                return true;

            return false;
        }

        /// <summary>
        /// 转换长文件名为短文件名
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="repstring"></param>
        /// <param name="leftnum"></param>
        /// <param name="rightnum"></param>
        /// <param name="charnum"></param>
        /// <returns></returns>
        public static string ConvertSimpleFileName(this string fullname, string repstring, int leftnum, int rightnum, int charnum)
        {
            string simplefilename = "", leftstring = "", rightstring = "", filename = "";
            string extname = fullname.GetFileExtName();

            if (extname.StrIsNullOrEmpty())
                throw new Exception("字符串不含有扩展名信息");

            int filelength = 0, dotindex = 0;

            dotindex = fullname.LastIndexOf('.');
            filename = fullname.Substring(0, dotindex);
            filelength = filename.Length;
            if (dotindex > charnum)
            {
                leftstring = filename.Substring(0, leftnum);
                rightstring = filename.Substring(filelength - rightnum, rightnum);
                if (repstring == "" || repstring == null)
                    simplefilename = leftstring + rightstring + "." + extname;
                else
                    simplefilename = leftstring + repstring + rightstring + "." + extname;
            }
            else
                simplefilename = fullname;

            return simplefilename;
        }

        /// <summary>
        /// 将字符串转换为Color
        /// </summary>
        /// <param name="color"></param>
        /// <returns></returns>
        public static Color ToColor(this string color)
        {
            int red, green, blue = 0;
            char[] rgb;
            color = color.TrimStart('#');
            color = Regex.Replace(color.ToLower(), "[g-zG-Z]", "");
            switch (color.Length)
            {
                case 3:
                    rgb = color.ToCharArray();
                    red = Convert.ToInt32(rgb[0].ToString() + rgb[0].ToString(), 16);
                    green = Convert.ToInt32(rgb[1].ToString() + rgb[1].ToString(), 16);
                    blue = Convert.ToInt32(rgb[2].ToString() + rgb[2].ToString(), 16);
                    return Color.FromArgb(red, green, blue);
                case 6:
                    rgb = color.ToCharArray();
                    red = Convert.ToInt32(rgb[0].ToString() + rgb[1].ToString(), 16);
                    green = Convert.ToInt32(rgb[2].ToString() + rgb[3].ToString(), 16);
                    blue = Convert.ToInt32(rgb[4].ToString() + rgb[5].ToString(), 16);
                    return Color.FromArgb(red, green, blue);
                default:
                    return Color.FromName(color);

            }
        }

        /// <summary>
        /// 将全角数字转换为数字
        /// </summary>
        /// <param name="SBCCase"></param>
        /// <returns></returns>
        public static string SBCCaseToNumberic(this string SBCCase)
        {
            char[] c = SBCCase.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
                if (b.Length == 2)
                {
                    if (b[1] == 255)
                    {
                        b[0] = (byte)(b[0] + 32);
                        b[1] = 0;
                        c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
                    }
                }
            }
            return new string(c);
        }

        /// <summary>
        /// 删除最后一个字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ClearLastChar(this string str)
        {
            return (str == "") ? "" : str.Substring(0, str.Length - 1);
        }

        /// <summary>
        /// 去掉指定的前缀字符串
        /// </summary>
        /// <param name="sourceString">原字符串</param>
        /// <param name="prefix">前缀</param>
        /// <param name="ignoreCase">是否忽略大小写</param>
        /// <returns></returns>
        public static string TrimPrefix(this string sourceString, string prefix, bool ignoreCase = false)
        {
            prefix = prefix ?? string.Empty;
            if (!sourceString.StartsWith(prefix, ignoreCase, CultureInfo.CurrentCulture))
            {
                return sourceString;

            }
            return sourceString.Remove(0, prefix.Length);
        }

        /// <summary>
        /// 去掉指定的后缀字符串
        /// </summary>
        /// <param name="sourceString">原字符串</param>
        /// <param name="suffix">后缀</param>
        /// <param name="ignoreCase">是否忽略大小写</param>
        /// <returns></returns>
        public static string TrimSuffix(this string sourceString, string suffix, bool ignoreCase = false)
        {
            suffix = suffix ?? string.Empty;
            if (!sourceString.EndsWith(suffix, ignoreCase, CultureInfo.CurrentCulture))
            {
                return sourceString;
            }
            return sourceString.Substring(0, sourceString.Length - suffix.Length);
        }

        /// <summary>
        /// 把字符串转换成枚举类型
        /// </summary>
        /// <typeparam name="T">枚举的泛型</typeparam>
        /// <param name="str">字符串</param>
        /// <param name="ignoreCase">是否忽略大小写</param>
        /// <returns></returns>
        public static T ToEnum<T>(this string str, bool ignoreCase)
        {
            return (T)Enum.Parse(typeof(T), str, ignoreCase);

        }

        /// <summary>
        /// 如果输入的字符串时空，就返回缺省字符串
        /// </summary>
        /// <param name="str">输入字符串</param>
        /// <param name="defaultStr">缺省字符串</param>
        /// <returns></returns>
        public static string ReturnDefaultRequired(this string str, string defaultStr)
        {
            if (string.IsNullOrEmpty(str))
            {
                return defaultStr.Trim();
            }

            return str.Trim();
        }

        /// <summary>
        /// 分割字符串，已字符串为分隔符
        /// </summary>
        /// <param name="strSource">原字符串</param>
        /// <param name="strSplit">分隔符字符串</param>
        /// <returns></returns>
        public static string[] StringSplit(this string strSource, string strSplit)
        {
            string[] strtmp = new string[1];
            int index = strSource.IndexOf(strSplit, 0);
            if (index < 0)
            {
                strtmp[0] = strSource;
                return strtmp;
            }
            else
            {
                strtmp[0] = strSource.Substring(0, index);
                return StringSplit(strSource.Substring(index + strSplit.Length), strSplit, strtmp);


            }
        }

        /// <summary>
        /// 分割字符串，已字符串为分隔符，不要直接调用，此方法是供上个重载的方法使用的。
        /// </summary>
        /// <param name="strSource">原字符串</param>
        /// <param name="strSplit">分隔符字符串</param>
        /// <param name="attachArray">字符串数组</param>
        /// <returns></returns>
        public static string[] StringSplit(this string strSource, string strSplit, string[] attachArray)
        {
            string[] strtmp = new string[attachArray.Length + 1];
            attachArray.CopyTo(strtmp, 0);

            int index = strSource.IndexOf(strSplit, 0);
            if (index < 0)
            {
                strtmp[attachArray.Length] = strSource;
                return strtmp;
            }
            else
            {
                strtmp[attachArray.Length] = strSource.Substring(0, index);
                return StringSplit(strSource.Substring(index + strSplit.Length), strSplit, strtmp);
            }
        }

        /// <summary>
        /// 从HTML中获取文本,保留br,p,img
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string GetTextFromHtml(this string strHtml)
        {
            Regex regEx = new Regex(@"</?(?!br|/?p|img)[^>]*>", RegexOptions.IgnoreCase);

            return regEx.Replace(strHtml, "");
        }

        /// <summary>
        /// 判断字符串是否含有中文
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static bool HasChina(this string str)
        {
            bool flag = false;
            for (int i = 0; i < str.Length; i++)
            {
                if (Convert.ToInt32(Convert.ToChar(str.Substring(i, 1))) > Convert.ToInt32(Convert.ToChar(128)))
                {
                    flag = true;
                }
            }
            return flag;
        }

        /// <summary>
        /// 判断字符串是否含有中文
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static bool CheckArithmeticExpressions(this string str)
        {
            string pattern = @"^(((?<o>\()[-+]?([0-9]+[-+*/])*)+[0-9]+((?<-o>\))([-+*/][0-9]+)*)+($|[-+*/]))*(?(o)(?!))$";
            return Regex.IsMatch("(" + str.Replace(" ", "") + ")", pattern);
        }

        /// <summary>
        /// 隔3位加逗号
        /// </summary>
        /// <param name="input">输入值</param>
        /// <param name="color">字体颜色</param>
        /// <returns></returns>
        public static String ToColorString(this String input, String css)
        {
            return "<span class='" + css + "'>" + input + "</span>";
        }

        /// <summary>
        /// POST数据传参
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="encode"></param>
        /// <returns></returns>
        public static string BuildQuery(IDictionary<string, string> parameters, string encode)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(name);
                    postData.Append("=");
                    if (encode == "gb2312")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                    }
                    else if (encode == "utf8")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    }
                    else
                    {
                        postData.Append(value);
                    }
                    hasParam = true;
                }
            }
            return postData.ToString();
        }

        public static JToken ReadJSON(this string jsonStr)
        {
            JObject jobj = JObject.Parse(jsonStr);
            JToken result = jobj as JToken;
            return result;
        }

        public static T DeserializeJsonToObject<T>(string json) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(json);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
            T t = o as T;
            return t;
        }

        /// <summary>
        /// 将字符串转换成base64格式,使用UTF8字符集
        /// </summary>
        /// <param name="content">加密内容</param>
        /// <returns></returns>
        public static string Base64Encode(string content)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(content);
            return Convert.ToBase64String(bytes);
        }


        /// <summary>
        /// 将base64格式，转换utf8
        /// </summary>
        /// <param name="content">解密内容</param>
        /// <returns></returns>
        public static string Base64Decode(this string content)
        {
            byte[] bytes = Convert.FromBase64String(content);
            return Encoding.UTF8.GetString(bytes);
        }

        /// <summary>
        /// 去掉换行符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string CleanString(this string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                return str.Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", "");
            }
            return "";
        }
    }
}
